package example.demo.route.handler;

import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sql.DataSource;
import java.lang.reflect.Field;

public abstract class SqlHandlerParent implements SqlHandlerInterface {
    protected DataSource dataSource;

    /*几个子类就调用几次，反正这个datasource会进入到老年代，一般数据源对象几乎不会被gc给清理掉*/
    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected Log getStatementLog(StatementHandler statementHandler) {
        try {
            Class<BaseStatementHandler> aClass = BaseStatementHandler.class;
            Field mappedStatementFiled = aClass.getDeclaredField("mappedStatement");
            mappedStatementFiled.setAccessible(true);
            MappedStatement mappedStatementO = (MappedStatement) mappedStatementFiled.get(statementHandler);
            return mappedStatementO.getStatementLog();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    protected Connection getConnection(StatementHandler statementHandler) {
//        /*获取数据库连接*/
//        Connection connection = DataSourceUtils.getConnection(dataSource);
//        return ConnectionLogger.newInstance(connection, getStatementLog(statementHandler), 1);
//    }
}
